<template>
<div id="file-view">
    <template v-if="isEdit && !onlyShow">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="继续上传" name="1"></el-tab-pane>
            <el-tab-pane label="已上传文件" name="2"></el-tab-pane>
        </el-tabs>
    </template>

    <template v-if="!onlyShow">
        <template v-if="activeName === '1' || !isEdit">
            <span v-if="accept !== ''" class="text-w">注意：请上传{{ accept }}格式文件</span>
            <div style="margin-top: 10px;">
                <el-upload
                    action="#"
                    ref="refFile"
                    list-type="picture-card"
                    :auto-upload="false"
                    :accept="accept"
                    :on-change="handleChange"
                    :multiple="isMultiple"
                    class="upload-s"
                >
                    <el-icon><Plus /></el-icon>
                    <template #file="{ file }">

                        <template v-if="file.name.split('.')[1] === 'jpeg' || file.name.split('.')[1] === 'jpg' || file.name.split('.')[1] === 'png'">
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        </template>

                        <template v-else>
                            <span class="file-s">{{ file.name }}</span>
                        </template>

                        <span class="el-upload-list__item-actions set-bg" style="background-color: rgba(0,0,0,.5)!important;">
                            <span
                                v-if="!disabled"
                                class="el-upload-list__item-delete"
                                @click="handleRemove(file)"
                                style="background: rgba(0,0,0,0)!important;"
                            >
                                <el-icon><Delete /></el-icon>
                            </span>
                        </span>

                    </template>
                </el-upload>
            </div>
        </template>
    </template>

    <template v-if="activeName === '2' && isEdit">
        <el-table
            class="heightcss"
            :data="fileData" 
            style="width: 100%"
            v-loading="loading"
            element-loading-background="rgba(0, 0, 0, 0.5)"
            border
        >
            <el-table-column
                prop="fileOriginName"
                label="附件名称"
                min-width="120"
                align="center"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                prop="fileSuffix"
                label="文件格式"
                min-width="120"
                align="center"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                prop="fileSizeKb"
                label="文件大小"
                min-width="100"
                align="center"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                prop="filePath"
                label="文件路径"
                min-width="140"
                align="center"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                fixed="right"
                prop="operation"
                label="操作"
                show-overflow-tooltip
                min-width="140"
                align="center"
            >
                <template #default="scope">
                    <!-- <el-link style="margin-right: 10px;" target="_blank" @click="viewClick(scope.row.id)" :href="scope.row.FilePath" type="primary">预览</el-link> -->
                    <el-button @click="viewClick(scope.row)" class="icon-e" text type="warning">预览</el-button>
                    <el-button @click="downClick(scope.row)" class="icon-e" text type="success">下载</el-button>
                    <el-button @click="delClick(scope.row.id)" class="icon-e" text type="danger">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </template>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , toRefs , toRaw , onMounted , watch, nextTick , watchEffect } from 'vue';
import { ElButton, ElMessage } from 'element-plus';
import { sysFileInfoPage , sysFileInfoDelete , sysFileInfoPreviewBase64 } from '/@/api/centerControl/pubilc';
export default defineComponent( {
    name: 'file-view',
    components: {},
    props: {
        fileInfo: {
            type: String,
            default: ''
        },
        isAccept: {
            type: String,
            default: ''
        },
        componentKey: {
            type: Number,
            default: 0
        },
        onlyShow: {
            type: Boolean,
            default: false
        },
        isMultiple: {
            type: Boolean,
            default: true,
        },
        isNeedRequest: {
            type: Boolean,
            default: true,
        },
    },
    setup(props,ctx){
        const fileList:any = ref([]);
        const refFile = ref();
        const disabled = ref(false);
        const isEdit = ref();
        const activeName = ref('1');
        const fileData = ref();
        const loading = ref(false);
        const viewDownPath = ref('');
        const accept = ref();
        const state = reactive({});
        const baseUrl = import.meta.env.VITE_API_URL as any;
        const ideView = import.meta.env.VITE_APP_API_VIEW_IDE;

        // 数据初始化
        onMounted(() => {
            nextTick(() => {
                fileList.value = [];
                accept.value = props.isAccept;
                isEdit.value = false;
                loading.value = false;
                if(props.onlyShow){
                    activeName.value = '2';
                    isEdit.value = true;
                    loading.value = true;
                }
                getPageFile();
            });
        })

        /*** handleChange 文件上传改变事件 */
        const handleChange = (file:any) => {
            fileList.value.push(file);
        }

        /*** 删除文件 */
        const handleRemove = (file:any) => {
            fileList.value.map((itm:any,inx:number) => {
                if(file.uid === itm.uid){
                    fileList.value.splice(inx,1)
                }
            });
            refFile.value.handleRemove(file);
        }

        /*** getPageFile 获取分页文件接口数据 */
        const getPageFile = () => {
            if(props.isNeedRequest){
                let setTime = setInterval(async() => {
                    if(props.fileInfo !== ''){
                        console.log(props.fileInfo,'props.fileInfo')
                        let param: any = {}
                        param.PageNo = 1;
                        param.PageSize = 99999;
                        param.sourceId = JSON.parse(props.fileInfo).sourceId;
                        let res: any = await sysFileInfoPage(param);
                        if(res.success && res.data.rows.length !== 0){
                            loading.value = true;
                            fileData.value = res.data.rows;
                            isEdit.value = true;
                            loading.value = false;
                        }else{
                            if(props.onlyShow) isEdit.value = true;
                            else isEdit.value = false;
                        }
                        loading.value = false;
                        clearInterval(setTime);
                    }
                }, 500);
            }
        }

        /*** handleClick 标签点击事件 */
        const handleClick = async (tab: any) => {
            activeName.value = toRaw(toRaw(tab).props).name;
        }

        /*** delClick 删除文件事件 */
        const delClick = async (val: Number) => {
            let param: any = {}
            param.id = val;
            let res: any = await sysFileInfoDelete(param);
            if(res.success) getPageFile();
        }

        // 将Base64编码数据转换为Blob对象的辅助函数
        const base64ToBlob = (base64Data: any) => {
            var byteString = atob(base64Data.split(',')[1]); // 提取Base64编码的数据部分
            var mimeString = base64Data.split(':')[1].split(';')[0]; // 提取MIME类型
            var ab = new ArrayBuffer(byteString.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            return new Blob([ab], {type: mimeString});
        }

        /*** viewClick 文件预览 */
        const viewClick = async (val: any) => {
            let viewUrl = baseUrl + 'api/Upload' + ideView + val.fileObjectName;
            window.open(viewUrl);
        }

        /*** downClick 下载文件 */
        const downClick = async (val: any) => {
            let getFile = getFileFun(val.id);
            // 等待getFileFun完成
            await getFile;
            if (getFile && getFile.then) {
                getFile.then(res => {
                    let base64Data = res;
                    let blob = base64ToBlob(base64Data);
                    
                    // 创建可下载的链接
                    let url = URL.createObjectURL(blob);
                    let link = document.createElement('a');
                    link.href = url;
                    link.download = val.fileOriginName; // 指定下载的文件名
                    
                    // 将链接添加到DOM中
                    document.body.appendChild(link);
                    
                    // 触发点击事件开始下载
                    link.click();
                    
                    // 释放临时URL
                    URL.revokeObjectURL(url);
                });
            }
        };

        /*** getFileFun 获取文件数据 */
        const getFileFun = async(val: Number) => {
            let param: any = {};
            param.id = val;
            let res: any = await sysFileInfoPreviewBase64(param);
            if(res.success) return res.data;
        }

        return{
            ...toRefs(state),
            handleChange,
            handleRemove,
            disabled,
            refFile,
            isEdit,
            activeName,
            handleClick,
            delClick,
            fileData,
            loading,
            viewClick,
            viewDownPath,
            downClick,
            accept,
            fileList,
        }
    }
})

</script>
<style lang="scss" scoped>
.upload-s{
    :deep(.el-upload--picture-card){
        background-color: rgba(255,255,255,0)!important;
    }
}
.text-w{
    font-size: 14px;
    color: #F56C6C;
}
</style>